package com.fw4j.jdbc.datasource.pool;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fw4j.configure.XmlParse;
import com.fw4j.configure.entity.Fw4jConfigure;
import com.fw4j.configure.entity.PoolConfigure;
import com.fw4j.jdbc.datasource.entity.Configure;

/**
 * @author 穆仁超
 * 数据库连接
 * 日期 2013-12-27 16:34
 * 我的QQ群：32894018
 */
public class DataSources {
	private static final Logger logger = LoggerFactory.getLogger(DataSources.class);
	private static java.sql.Connection conn = null;
	private volatile Map<String,ConnectionPool> pool = new HashMap<String,ConnectionPool>();
	private Configure conf = null;
	private static DataSources instance = null;
	
	public static DataSources getInstance(){
		if(instance == null){
			instance = new DataSources();
		}
		return instance;
	}

	private DataSources(){
		 try {
			 Fw4jConfigure fw4jConfigure = XmlParse.getInstance().getFw4jCnfigure();
//			 InputStream in = ClassLoader.getSystemResourceAsStream("db.properties");
//			 Properties p = new Properties();
//			 p.load(in);
//			 if(Boolean.parseBoolean(p.getProperty("db.pool")) == true){
//				 this.conf = new Configure((String)p.getProperty("db.url"), (String)p.getProperty("db.user"), 
//						 (String)p.getProperty("db.pwd"),(String)p.getProperty("db.driver"),true);
//			 }else{
//				 this.conf = new Configure((String)p.getProperty("db.url"), (String)p.getProperty("db.user"),
//						 (String)p.getProperty("db.pwd"), (String)p.getProperty("db.driver"));
//			 }
			 Map<String,PoolConfigure> pcMap = fw4jConfigure.getPconfigure();
			 PoolConfigure pc = pcMap.get("default");
			 conf = new Configure(pc.getUrl(),pc.getUser(),pc.getPwd(),pc.getDriver(),pc.isPool());
			 //多数据库支持
			 pool.put(conf.getDatabase(), new ConnectionPool(conf));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
//	public static java.sql.Connection getInstance() throws SQLException{
//		if(conn == null){
//			conn = new Connect().getConnection();
//		}
//		return conn;
//	}
//	public static void setConn(java.sql.Connection c){
//		conn = c;
//	}
	
	public java.sql.Connection getConnection(String database){
		return this.pool.get(database).getConnection();	
	}
	
	public java.sql.Connection getConnection(){
		return this.getConnection("default");	
	}
}
